/**
 * 跨省销售用产地检疫申报单(动物B)
 * @constructor
 */
function Approval2() {
}

Approval2.init = function () {
    addSelect();
    $('#tableList').bootstrapTable({
        url: '/saleDeclarationB/tableSearch',
        method: 'post',
        striped: true, //是否显示行间隔色
        toolbar: "#toolbar",
        sidePagination: "true",
        dataField: "data",//这是返回的json数组的key.默认是"rows".这里只有前后端约定好就行
        showToggle: true, //是否显示详细视图和列表视图的切换按钮
        striped: true, // 是否显示行间隔色
//search : "true",
        uniqueId: "id",
        pageList: [5, 10, 20, 50, 100],//可选择单页记录数
        pageSize: "10",
        pagination: true, // 是否分页
        sortable: true, // 是否启用排序
        sidePagination: 'server', // 设置为服务器端分页     客户端：client
        search: false,
        showColumns: true,
        showRefresh: true,
        showExport: true,
//得到查询的参数
        queryParams: function (params) {
//这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            var query_params = {
//********table的参数 不变
                pageSize: params.limit,                         //页面大小
                pageIndex: (params.offset / params.limit) + 1,   //页码
                sort: params.sort,      //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
//********
//获取查询的对象，往下加入
                timeInterval: $('#search_SaleDate').val(), // 请求时向服务端传递的参数
                types: $('#search_types').val(), // 请求时向服务端传递的参数

            };
            return query_params;
        },
        columns: [
            {
//field: 'Number',//可不加
                title: '序号',//标题  可不加
                align: "center",
                width: 40,
                formatter: function (value, row, index) {
                    var pageSize = $('#tableList').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                    var pageNumber = $('#tableList').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                    return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                }
            },
            {field: 'declarant', title: '申报人(个人填写名字,单位填写单位全称)', align: 'center'},
            {field: 'phone', title: '联系电话', align: 'center'},
            {field: 'buyer', title: '购买人', align: 'center'},
            {field: 'buyerPhone', title: '购买人电话', align: 'center'},
            {field: 'animalType', title: '饲养动物种类', align: 'center'},
            {field: 'saleAnimalType', title: '销售动物种类', align: 'center'},
            {field: 'batchNumber', title: '批次号', align: 'center'},
            {field: 'number', title: '数量(头、羽)', align: 'center'},
            {field: 'starEar', title: '起始耳标号', align: 'center'},
            {field: 'endEar', title: '结束耳标号', align: 'center'},
            {field: 'purpose', title: '用途', align: 'center'},
            {field: 'starAddress', title: '启运地点', align: 'center'},
            {field: 'villageName', title: '村名', align: 'center'},
            {field: 'nowAddress', title: '当前地点', align: 'center'},
            {field: 'fullArriveAddress', title: '到达地点', align: 'center'},
            {field: 'slaughter', title: '屠宰或饲养场全称', align: 'center'},
            {
                field: 'animalPhoto', title: '动物状态图片',align: 'center',width: 200,
                formatter: function (value) {
                    return "<a href='"+value+"' target='_blank'>查看图片</a>";
                    // return "<img src=\"" + value + "\" class=\"img-responsive\">";
                }
            },
            {
                field: 'carPhoto', title: '动物运载车辆图片',align: 'center',width: 200,
                formatter: function (value) {
                    return "<a href='"+value+"' target='_blank'>查看图片</a>";
                    // return "<img src=\"" + value + "\" class=\"img-responsive\">";
                }
            },
            {field: 'saleDate', title: '销售时间', align: 'center'},
            {
                field: 'reportPhoto', title: '检测报告单照片(猪售辖区外禽类跨省出售)',align: 'center',width: 200,
                formatter:function(value){
                    return "<img src=\""+value+"\" class=\"img-responsive\">";
                }
            },
            {
                field: 'certificatePhoto', title: '准调证照片(出售到永安辖区外,本省内时)',align: 'center',width: 200,
                formatter:function(value){
                    return "<img src=\""+value+"\" class=\"img-responsive\">";
                }
            },
            {
                field: 'agriculturePhoto', title: '农产品合格证/追溯码照片',align: 'center',width: 200,
                formatter: function (value) {
                    return "<a href='"+value+"' target='_blank'>查看图片</a>";
                    // return "<img src=\"" + value + "\" class=\"img-responsive\">";
                }
            },
            {
                field: 'pigCarPhoto', title: '其它照片',align: 'center',width: 200,
                formatter: function (value) {
                    return "<a href='"+value+"' target='_blank'>查看图片</a>";
                    // return "<img src=\"" + value + "\" class=\"img-responsive\">";
                }
            },
            {field: 'remark', title: '备注', align: 'center'},
            {
                field: 'types', title: '审批状态', align: 'center',
                formatter:function (value) {
                    if (value == 0) return "待审";
                    else if (value == 1) return "驳回";
                    else if (value == 2) return "待出证";
                    else if (value == 3) return "已出证";
                }
            },
            {
                title: '操作',
                align: 'center',
                formatter: function (value, row, index) {
                    var optionHtml = "";
                    if (row.types == 0){
                        optionHtml = optionHtml + "<a class=\"btn btn-success btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"aproval\")' title=\"审批\" ><i class=\"fa fa-edit\"></i>审批</a>";
                    }else if (row.types == 2){
                        optionHtml = optionHtml + "<a class=\"btn btn-warning btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"certificate\")' title=\"出证\" ><i class=\"fa fa-edit\"></i>出证</a>";
                    }
                    optionHtml = optionHtml + "<a class=\"btn btn-info btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"show\")' title=\"查看详情\" ><i class=\"fa\"></i>查看详情</a>";
                    return optionHtml;

                }
            }
        ]
    });
}

//查询方法****************************
function doSearch() {
// $('#tableList').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
    $("#tableList").bootstrapTable("refreshOptions", {pageNumber: 1});
}

//重置****************************
function doRest() {
    $("#search_SaleDate").val("");
// $('#tableList').bootstrapTable(('refresh')); // 很重要的一步，刷新url！
    $("#tableList").bootstrapTable("refreshOptions", {pageNumber: 1});
}

//增加方法****************************
var Action = "";
var id = 0;
var pxt = "/saleDeclarationB"; //控制器名称
function addRecord() {
    id = 0;
    Action = "add";
    $("#myform")[0].reset();
}

//增加/修改数据保存****************************
function saveRecord() {
    let purpose = "";
    $.each($("#text_purpose input[type=checkbox]:checked"), function () {
        purpose += $(this).val() + ","
    })
    purpose = purpose.substring(0, purpose.length - 1)
    if (!validateForm()) return false;
//创建传递的参数
    var postdata = {
        id: id,
        action:Action,
        types:$("#types").val(),
        opinion:$("#opinion").val(),
        witness:$("#witness").val(),
        livestock:$("#livestock").val(),
    };
// console.log(JSON.stringify(postdata));
//发送异步请求到后台保存用户数据
    $.ajax({
        url: pxt + "/action",
        type: "post",
        data: JSON.stringify(postdata),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            if (data.code === "200") {
                $('#myModalAdd').modal('hide')
                doSearch();
                swal("操作成功!",data.message, "success");
            }else {
                swal("操作失败!", data.message, "error");
            }
        }
    });
}

//操作相关方法****************************
function actionRecord(data, type) {
    httpAnimalPhoto=data.animalPhoto;
    httpCarPhoto=data.carPhoto;
    httpPigCarPhoto=data.pigCarPhoto;
    httpReportPhoto=data.reportPhoto;
    httpCertificatePhoto=data.certificatePhoto;
    httpAgriculturePhoto=data.agriculturePhoto;
    if (type == "aproval") { //审批
        id = data.id;
        Action = "aproval";
        $("#myform")[0].reset();
        $("#Aproval").show();
        $("#Certificate").hide();
        $("#save").removeAttr("disabled");
        WriteData(data)
        $('#myModalAdd').modal('show')
    }else if (type == "certificate") { //出证
        id = data.id;
        Action = "certificate";
        $("#myform")[0].reset();
        $("#Aproval").hide();
        $("#Certificate").show();
        $("#save").removeAttr("disabled");
        WriteData(data)
        $('#myModalAdd').modal('show')
    }else if (type == "show"){ //详情
        id = data.id;
        Action = "show";
        $("#myform1")[0].reset();
        WriteData1(data)
        $('#myModalAdd1').modal('show')
    }
}

//给控件赋值****************************
function WriteData(data) {
    $("#text_declarant").val(data.declarant);
    $("#text_phone").val(data.phone);
    $("#text_buyer").val(data.buyer);
    $("#text_buyerPhone").val(data.buyerPhone);
    $("#text_animalType").val(data.animalType);
    $("#text_number").val(data.number);
    $("#text_starEar").val(data.starEar);
    $("#text_endEar").val(data.endEar);
    $("#text_purpose").val(data.purpose);
    $("#text_saleAnimalType").val(data.saleAnimalType);
    $("#text_starAddress").val(data.starAddress);
    $("#text_villageName").val(data.villageName);
    $("#text_nowAddress").val(data.nowAddress);
    $("#text_fullArriveAddress").val(data.fullArriveAddress);
    $("#text_slaughter").val(data.slaughter);
    $("#showImage").attr("src",httpAnimalPhoto);
    $("#showImage2").attr("src",httpCarPhoto);
    $("#showImage3").attr("src",httpPigCarPhoto);
    $("#text_saleDate").val(data.saleDate);
    $("#showImage4").attr("src",httpReportPhoto);
    $("#showImage5").attr("src",httpCertificatePhoto);
    $("#showImage6").attr("src",httpAgriculturePhoto);
    $("#text_remark").val(data.remark);
}
//给控件赋值****************************
function WriteData1(data) {
    $("#declarant").val(data.declarant);
    $("#phone").val(data.phone);
    $("#buyer").val(data.buyer);
    $("#buyerPhone").val(data.buyerPhone);
    $("#animalType").val(data.animalType);
    $("#number").val(data.number);
    $("#starEar").val(data.starEar);
    $("#endEar").val(data.endEar);
    $("#purpose").val(data.purpose);
    $("#saleAnimalType").val(data.saleAnimalType);
    $("#starAddress").val(data.starAddress);
    $("#villageName").val(data.villageName);
    $("#nowAddress").val(data.nowAddress);
    $("#fullArriveAddress").val(data.fullArriveAddress);
    $("#slaughter").val(data.slaughter);
    $("#Image").attr("src",httpAnimalPhoto);
    $("#Image2").attr("src",httpCarPhoto);
    $("#Image3").attr("src",httpPigCarPhoto);
    $("#saleDate").val(data.saleDate);
    $("#Image4").attr("src",httpReportPhoto);
    $("#Image5").attr("src",httpCertificatePhoto);
    $("#Image6").attr("src",httpAgriculturePhoto);
    $("#remark").val(data.remark);
    $("#aprovalUser").val(data.aproval);
    $("#aprovalTime").val(data.aprovalTime);
    $("#aprovalOpinion").val(data.opinion);
    $("#certificateUser").val(data.certificate);
    $("#certificateTime").val(data.certificateTime);
    $("#certificateUserName").val(data.witness);
    $("#livestockName").val(data.livestock);
    let types = "";
    if (data.types == 0) types = "待审";
    else if (data.types == 1) types = "驳回";
    else if (data.types == 2) types = "待出证";
    else if (data.types == 3) types = "已出证";
    $("#aprovalType").val(types);
}
var animalPhoto="";//动物状态图片路径
var httpAnimalPhoto="";//动物状态图片完整路径
//上传****************************
function ImportShipmentStatusList() {
    console.log("进入图片上传方法")
    var upname = "text_animalPhoto";
    if ($("#" + upname).val() == "") {
        alert("请选择上传图片");
        return;
    }
    $.ajaxFileUpload({
        url: pxt+'/uploadImages',
        secureuri: false,
        fileElementId: upname,
        dataType: 'json',
        success: function (data, status) {
            animalPhoto = data.url;
            //图片回显
            $("#showImage").css("display","");
            $("#showImage").attr("src",data.httpUrl);
        },
        error: function (data, status, e) {
            console.log("上传图片失败",e);
        }
    });
}
var carPhoto="";//动物运载车辆图片路径
var httpCarPhoto="";//动物运载车辆图片完整路径
//上传****************************
function ImportShipmentStatusList2() {
    console.log("进入图片上传方法")
    var upname = "text_carPhoto";
    if ($("#" + upname).val() == "") {
        alert("请选择上传图片");
        return;
    }
    $.ajaxFileUpload({
        url: pxt+'/uploadImages',
        secureuri: false,
        fileElementId: upname,
        dataType: 'json',
        success: function (data, status) {
            carPhoto = data.url;
            //图片回显
            $("#showImage2").css("display","");
            $("#showImage2").attr("src",data.httpUrl);
        },
        error: function (data, status, e) {
            console.log("上传图片失败",e);
        }
    });
}
var pigCarPhoto="";//生猪运输车辆备案表图片路径
var httpPigCarPhoto="";//生猪运输车辆备案表图片完整路径
//上传****************************
function ImportShipmentStatusList3() {
    console.log("进入图片上传方法")
    var upname = "text_pigCarPhoto";
    if ($("#" + upname).val() == "") {
        alert("请选择上传图片");
        return;
    }
    $.ajaxFileUpload({
        url: pxt+'/uploadImages',
        secureuri: false,
        fileElementId: upname,
        dataType: 'json',
        success: function (data, status) {
            pigCarPhoto = data.url;
            //图片回显
            $("#showImage3").css("display","");
            $("#showImage3").attr("src",data.httpUrl);
        },
        error: function (data, status, e) {
            console.log("上传图片失败",e);
        }
    });
}
var reportPhoto="";//检测报告单照片路径
var httpReportPhoto="";//检测报告单照片完整路径
//上传****************************
function ImportShipmentStatusList4() {
    console.log("进入图片上传方法")
    var upname = "text_reportPhoto";
    if ($("#" + upname).val() == "") {
        alert("请选择上传图片");
        return;
    }
    $.ajaxFileUpload({
        url: pxt+'/uploadImages',
        secureuri: false,
        fileElementId: upname,
        dataType: 'json',
        success: function (data, status) {
            reportPhoto = data.url;
            //图片回显
            $("#showImage4").css("display","");
            $("#showImage4").attr("src",data.httpUrl);
        },
        error: function (data, status, e) {
            console.log("上传图片失败",e);
        }
    });
}
var certificatePhoto="";//准调证照片路径
var httpCertificatePhoto="";//准调证照片完整路径
//上传****************************
function ImportShipmentStatusList5() {
    console.log("进入图片上传方法")
    var upname = "text_certificatePhoto";
    if ($("#" + upname).val() == "") {
        alert("请选择上传图片");
        return;
    }
    $.ajaxFileUpload({
        url: pxt+'/uploadImages',
        secureuri: false,
        fileElementId: upname,
        dataType: 'json',
        success: function (data, status) {
            certificatePhoto = data.url;
            //图片回显
            $("#showImage5").css("display","");
            $("#showImage5").attr("src",data.httpUrl);
        },
        error: function (data, status, e) {
            console.log("上传图片失败",e);
        }
    });
}
var agriculturePhoto="";//农产品合格证照片路径
var httpAgriculturePhoto="";//农产品合格证照片完整路径
//上传****************************
function ImportShipmentStatusList6() {
    console.log("进入图片上传方法")
    var upname = "text_agriculturePhoto";
    if ($("#" + upname).val() == "") {
        alert("请选择上传图片");
        return;
    }
    $.ajaxFileUpload({
        url: pxt+'/uploadImages',
        secureuri: false,
        fileElementId: upname,
        dataType: 'json',
        success: function (data, status) {
            agriculturePhoto = data.url;
            //图片回显
            $("#showImage6").css("display","");
            $("#showImage6").attr("src",data.httpUrl);
        },
        error: function (data, status, e) {
            console.log("上传图片失败",e);
        }
    });
}
//到达城市三级联动**************************
function loadCities() {
    $.ajax({
        url: "/city/tableSearch",
        type:"post",
        data:JSON.stringify({pageSize: 100}),
        contentType:"application/json",
        dataType:"json",
        success:function(data){
            initCitySelect(data.data);
            if(data.data[0]){
                loadDistricts(data.data[0].city_id)
            }
        }
    });
}


function loadDistricts(city) {
    $.ajax({
        url: "/district/tableSearch",
        type:"post",
        data:JSON.stringify({city_id:$(city).val(),pageSize: 100}),
        contentType:"application/json",
        dataType:"json",
        success:function(data){
            initDistrictSelect(data.data);
            if(data.data[0]){
                loadTowns(data.data[0].district_id)
            }
        }
    });
}


function loadTowns(district) {
    $.ajax({
        url: "/town/tableSearch",
        type:"post",
        data:JSON.stringify({district_id:$(district).val(),pageSize: 100}),
        contentType:"application/json",
        dataType:"json",
        success:function(data){
            initTownSelect(data.data);
        }
    });
}

function initCitySelect(data) {
    $('#text_arriveCity').empty();
    $.each(data,function (index,item) {
        $('#text_arriveCity').append("<option value='"+item.city_id+"'>"+item.city_name+"</option>");
    })
}

function initDistrictSelect(data) {
    $('#text_arriveDistrict').empty();
    $.each(data,function (index,item) {
        $('#text_arriveDistrict').append("<option value='"+item.district_id+"'>"+item.district_name+"</option>");
    })
}

function initTownSelect(data) {
    $('#text_arriveTownship').empty();
    $.each(data,function (index,item) {
        $('#text_arriveTownship').append("<option value='"+item.town_id+"'>"+item.town__name+"</option>");
    })
}
$("#types").change(function () {
    addSelect();
});
//给下拉选赋值*****************************
function addSelect() {
    let type = $("#types").val();
    if (type == 2)
        type = 0;
    else
        type = 1;
    $.ajax({
        type: "get",
        url: "/approvalOpinion/selectByType?type="+type,
        dataType: "json",
        contentType: "application/json",
        success: function (data, status) {
            if (data.code == "200") {
                $("#opinion").empty();
                $.each(data.data,function (i,v) {
                    $("#opinion").append("<option value=\""+v.approvalOpinion+"\">"+v.approvalOpinion+"</option>");
                })
            }
        }
    });
}
//表单验证*****************************
function validateForm() {
//validate方法参数可选
    return $("#myform").validate({
        rules: {

            text_declarant: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_phone: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_buyer: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_buyerPhone: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_animalType: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_number: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_starEar: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endEar: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_purpose: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_starAddress: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_villageName: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_nowAddress: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_arriveAddress: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_slaughter: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_saleDate: {
                required: true,//必填
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
        },
//错误信息提示
        messages: {
            text_declarant: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_phone: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_buyer: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_buyerPhone: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_animalType: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_number: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_starEar: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_endEar: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_purpose: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_starAddress: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_villageName: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_nowAddress: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_arriveAddress: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_slaughter: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
            text_saleDate: {
                required: "(必填)",
                minlength: 1, //最少1个字符
                maxlength: 50,//最多50个字符
                // number: true, //必须是数字
            },
        },
    }).form();

}
